#!/usr/bin/env python3
"""Convert relative transform JSON to absolute transform JSON."""

import json
import sys
import math

def convert_relative_to_absolute(relative_json_path, neutral_json_path, output_json_path):
    """Convert relative transform parameters to absolute values."""
    with open(relative_json_path, 'r') as f:
        relative_data = json.load(f)
    with open(neutral_json_path, 'r') as f:
        neutral_data = json.load(f)
    
    absolute_data = relative_data.copy()
    
    for part_name, part_configs in absolute_data.items():
        if part_name in neutral_data:
            neutral_stretch = neutral_data[part_name]["stretch"]
            neutral_pyramid = neutral_data[part_name]["pyramid"]
            
            for config in part_configs:
                if config["tool"] == "stretch":
                    params = config["param_range"]
                    for i, axis in enumerate(['x', 'y', 'z']):
                        if axis in params:
                            if isinstance(params[axis], list):
                                params[axis] = [params[axis][0] * neutral_stretch[i], 
                                              params[axis][1] * neutral_stretch[i]]
                            else:
                                params[axis] = params[axis] * neutral_stretch[i]
                
                elif config["tool"] == "pyramid":
                    params = config["param_range"]
                    pyramid_keys = ['xp', 'xm', 'yp', 'ym', 'zp', 'zm']
                    for i, key in enumerate(pyramid_keys):
                        if key in params:
                            if isinstance(params[key], list):
                                params[key] = [params[key][0]**2 * neutral_pyramid[i], 
                                             params[key][1]**2 * neutral_pyramid[i]]
                            else:
                                params[key] = params[key]**2 * neutral_pyramid[i]
        else:
            print(f"Warning: No neutral data found for part '{part_name}', keeping relative values")
    
    with open(output_json_path, 'w') as f:
        json.dump(absolute_data, f, indent=2, default=lambda x: f"{x:.6f}" if isinstance(x, float) else x)
    print(f"Conversion completed. Output saved to {output_json_path}")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python convert_relative_to_absolute.py <relative_json> <neutral_json> <output_json>")
        sys.exit(1)
    
    convert_relative_to_absolute(sys.argv[1], sys.argv[2], sys.argv[3]) 